<!-- 任务中心的选择班级 -->
<template>
  <el-cascader
    placeholder="请选择班级"
    class="class-search"
    popper-class="task-class-search"
    v-model="classValue"
    :options="treeData"
    :popper-append-to-body="false"
    :clearable="false"
    @change="reNewCurrentClass"
  ></el-cascader>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAuthStore } from '@/stores'
import { storeToRefs } from 'pinia'

const props = defineProps({
  isClassDefault: {
    type: Boolean,
    default: false
  },
  defaultClass: {
    type: Array,
    default: () => []
  },
  showAll: {
    type: Boolean,
    default: false
  }
})

const authStore = useAuthStore()
const { getClassListOfSubject, getTeachingInfo } = authStore

const { nowGlobalSubjectId, nowGlobalRole, nowGlobalStageId } =
  storeToRefs(authStore)

const currentClass = defineModel('currentClass') // [年级 class_id class_type grade_num] 靶向班的 [0 class_id class_type grade_num]
const classValue = ref([])
const treeData = ref([])

watch(
  [
    () => nowGlobalSubjectId.value,
    () => nowGlobalRole.value,
    () => nowGlobalStageId.value
  ],
  () => {
    initData()
  },
  {
    deep: true
  }
)

const initData = async () => {
  treeData.value = []
  await getTeachingInfo(nowGlobalRole.value.role_code)
  if (props.showAll) {
    treeData.value = [{ value: 0, label: '全部班级' }]
  }
  let tree = await getClassListOfSubject(nowGlobalSubjectId.value)
  treeData.value.push(...tree)
  if (props.defaultClass.length) {
    // 判断传入的默认值是否在树结构中
    let resNode = null
    let parent = treeData.value.find(
      item => item.value === props.defaultClass[0]
    )
    resNode =
      parent &&
      parent.children.find(item => item.value === props.defaultClass[1])
    if (resNode) {
      classValue.value = props.defaultClass
    } else {
      classValue.value = [
        treeData.value[0].value,
        treeData.value[0].children[0].value
      ]
    }
  } else if (props.isClassDefault && treeData.value.length) {
    classValue.value = [
      treeData.value[0].value,
      treeData.value[0].children[0].value
    ]
  }

  reNewCurrentClass()
}

const reNewCurrentClass = () => {
  if (classValue.value.length <= 1) {
    currentClass.value = classValue.value
    return
  }
  let parent = treeData.value.find(
    item => item.value === classValue.value[0] && item.children
  )
  if (parent) {
    let target = parent?.children.find(
      item => item.value === classValue.value[1]
    )
    currentClass.value = [
      ...classValue.value,
      target.class_type,
      parent.value || target.grade_num
    ]
  }
}

initData()
</script>

<style lang="less" scoped></style>
